package com.example.wwk.graduationpractice.AsyncTask;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;


import com.example.wwk.graduationpractice.Activity.LoginActivity;
import com.example.wwk.graduationpractice.Fragment.MainActivity;
import com.example.wwk.graduationpractice.Globalutils.ActivityCollector;
import com.example.wwk.graduationpractice.Globalutils.SharedPreferenceUtils;
import com.example.wwk.graduationpractice.NetDataUtils.GroupUtils;
import com.example.wwk.graduationpractice.R;
import com.example.wwk.graduationpractice.Globalutils.CustomDialogUtils;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.Globalutils.PromptShowUtils;
import com.example.wwk.graduationpractice.SmackUtils.GetOfflineMsgUtils;
import com.example.wwk.graduationpractice.SmackUtils.ReConnectionListener;
import com.example.wwk.graduationpractice.SmackUtils.XmppConnectUtils;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import java.io.IOException;

/**
 * Created by wwk on 2017/3/16.
 */

public class LoginAsyncTask extends AppCompatActivity {

    public static final int NOT_NETWORK = 1;
    public static final int CONFLICT = 2;
    //handler
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case NOT_NETWORK:
                    String title = "提示";
                    String message = "当前网络不可达,请检查网络状态！";
                    Activity activity = ActivityCollector.getTopActivity();
                    PromptShowUtils.showDialog(title, message, activity);
                    break;
                case CONFLICT:  //已有用户登录，登录冲突
                    String title2 = "警告";
                    String message2 = "您的账号在别处登录！";
                    Activity activity2 = ActivityCollector.getTopActivity();
                    PromptShowUtils.showDialog(title2, message2, activity2);
                    break;
            }
        }
    };


    public static void login(final int identity, final Context context, final SharedPreferences pref, final SharedPreferences.Editor editor,
                             final boolean check, final String user, final String pwd) { //登录按钮的事件,获取输入的用户名和密码
        new AsyncTask<String, String, Integer>() {//传入任务的参数类型；显示进度的单位；返回结果类型

            private CustomDialogUtils progressDialog;
            private AbstractXMPPConnection connection;
            //用户群
            private String groupName;

            @Override
            protected void onPreExecute() {              //任务开始前执行，一些初始化操作
                if (TextUtils.isEmpty(user) || TextUtils.isEmpty(pwd)) {
                    PromptShowUtils.showToast("账号或密码不能为空");
                    return;
                }
                progressDialog = new CustomDialogUtils(context, R.style.CustomDialog);
                progressDialog.setCancelable(false);        //无法手动取消
                progressDialog.show();

            }

            @Override
            protected Integer doInBackground(String... strings) {        //异步线程执行任务
                try {
                    boolean checkIdentity;
                    //身份判断，选择不同的用户群组
                    if (identity == LoginActivity.USER)
                        groupName = "user";
                    else
                        groupName = "doctor";
                    //判断在该群组（该身份）是否存在该用户
                    if (GroupUtils.getAlreadyUser(user, groupName).getAlreadyUser() == 0)
                        return -1;
                    else
                        checkIdentity = true;
                    //当身份验证通过
                    if (checkIdentity) {
                        connection = XmppConnectUtils.getConnection();//获取连接
                        connection.login(user, pwd);
                        GetOfflineMsgUtils.getOffMessages(connection);      //获取离线消息
                        Presence presence2 = new Presence(Presence.Type.available);
                        presence2.setStatus("在线");
                        connection.sendStanza(presence2);       //设置状态
                        MyApplication.setConnection(connection);
                        connection.addConnectionListener(new ReConnectionListener(handler));   //设置 连接的监听
                        return 1;
                    }
                } catch (XMPPException e) {
                    e.printStackTrace();
                    return -3;
                } catch (SmackException.NotConnectedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SmackException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    return -2;
                }
                return -4;
            }

            @Override
            protected void onPostExecute(Integer type) {
                //任务执行结束后，并返回数据（作为该方法的参数），根据不同的处理结果进行UI操作
                if (type == 1) {
                    rememberPwdApply(pref, editor, check, user, pwd);       //登录成功时判断 记住密码checkBox的逻辑
                    Intent intent1 = new Intent(context, MainActivity.class);
                    intent1.putExtra("user", user);
                    intent1.putExtra("identity", identity);
                    context.startActivity(intent1);
                } else if(type == -1)
                    PromptShowUtils.showDialog("警告", "登录失败，请检验您的登录身份！", context);
                else if(type == -2)
                    PromptShowUtils.showDialog("警告", "登录失败，服务器或网络异常！", context);
                else if(type == -3)
                    PromptShowUtils.showDialog("警告", "登录失败，请检验您的账号及密码！", context);
                progressDialog.dismiss();


            }
        }.execute();//启动
    }
    /*
    登录成功时判断 记住密码checkBox的逻辑
    */
    private static void rememberPwdApply(SharedPreferences pref, SharedPreferences.Editor editor, boolean check, String user, String pwd) {
        editor = SharedPreferenceUtils.getSharedEditor();           //登录的记住密码，采用SharedPreferences
        if (check) {//记住密码是否被选中
            //true
            editor.putBoolean("remember_password", true);
            editor.putString("user", user);
            editor.putString("password", pwd);
        } else {
            //false
            editor.clear();
        }
        editor.apply();
    }


}
